from time import sleep

from selenium.webdriver.common.by import By


def ID(driver, value, plural=False):
    if plural:
        return driver.find_elements(By.ID, value)
    else:
        return driver.find_element(By.ID, value)


def NAME(driver, value, plural=False):
    if plural:
        return driver.find_elements(By.NAME, value)
    else:
        return driver.find_element(By.NAME, value)


def CLASS_NAME(driver, value, plural=False):
    if plural:
        return driver.find_elements(By.CLASS_NAME, value)
    else:
        return driver.find_element(By.CLASS_NAME, value)


def TAG_NAME(driver, value, plural=False):
    if plural:
        return driver.find_elements(By.TAG_NAME, value)
    else:
        return driver.find_element(By.TAG_NAME, value)


def LINK_TEXT(driver, value, plural=False):
    if plural:
        return driver.find_elements(By.LINK_TEXT, value)
    else:
        return driver.find_element(By.LINK_TEXT, value)


def PARTIAL_LINK_TEXT(driver, value, plural=False):
    if plural:
        return driver.find_elements(By.PARTIAL_LINK_TEXT, value)
    else:
        return driver.find_element(By.PARTIAL_LINK_TEXT, value)


def XPATH(driver, value, plural=False):
    if plural:
        return driver.find_elements(By.XPATH, value)
    else:
        return driver.find_element(By.XPATH, value)


def CSS_SELECTOR(driver, value, plural=False):
    if plural:
        return driver.find_elements(By.CSS_SELECTOR, value)
    else:
        return driver.find_element(By.CSS_SELECTOR, value)


def default():
    print('No such case')


def select(driver, by_value, plural=False):
    switch = {
        'ID': ID,
        'NAME': NAME,
        'CLASS_NAME': CLASS_NAME,
        'TAG_NAME': TAG_NAME,
        'LINK_TEXT': LINK_TEXT,
        'PARTIAL_LINK_TEXT': PARTIAL_LINK_TEXT,
        'XPATH': XPATH,
        'CSS_SELECTOR': CSS_SELECTOR
    }
    try:
        # 执行对应的函数，如果没有就执行默认的函数
        return switch.get(by_value[2], default)(driver, by_value[3], plural)
    except Exception as e:
        try:
            # print(e)
            print(by_value[1], "元素未找到,进行重新寻找")
            sleep(2)
            # 执行对应的函数，如果没有就执行默认的函数
            return switch.get(by_value[2], default)(driver, by_value[3], plural)
        except Exception as e:
            # print(e)
            print(by_value[1], "出现异常，元素未找到")
            print("data下标为：", by_value[0])


# 以下为模块测试代码
if __name__ == '__main__':
    pass
